package com.binguo.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.binguo.api.baidu.BaiduRecUtil;
import com.binguo.api.baidu.BaiduRecUtilWithPallet;
import com.binguo.api.baidu.BaiduRecUtilWithPlate;
import com.binguo.api.businessmodel.ProductImgModel;
import com.binguo.api.form.ProductCorrectForm;
import com.binguo.api.form.ProductRecForm;
import com.binguo.api.form.ShopProductVersionForm;
import com.binguo.api.response.api.BaseChargeResp;
import com.binguo.api.response.product.ProductRecResultDetailVO;
import com.binguo.api.response.product.ProductRecResultVO;
import com.binguo.api.response.product.ProductRecResultVONewWithLocation;
import com.binguo.api.result.Result;
import com.binguo.api.result.ResultGenerator;
import com.binguo.api.schedule.DataLoadService;
import com.binguo.api.service.RuiJingService;
import com.binguo.api.yprecapi.YpRecUtilWithPlateAndNoCutService;
import com.binguo.api.yprecapi.YpRecUtilWithPlateService;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.util.ImageBase64Util;
import com.binguo.common.util.JsonUtil;
import com.binguo.model.api.vo.MinorCategoryVO;
import com.binguo.model.api.vo.ProductVO;
import com.binguo.model.mapper.BranchMapper;
import com.binguo.model.mapper.LogProductImgFromUserMapper;
import com.binguo.model.mapper.ProductSubMapper;
import com.binguo.model.model.*;
import com.binguo.service.ProductService;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

import sun.misc.BASE64Decoder;
import tk.mybatis.mapper.entity.Condition;

/**
 * Created by haibang on 18/5/7.
 */
@Api(tags = "收银端: 菜品")
@RestController
@RequestMapping
public class ProductController {

    private static Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    ProductService productService;

    @Resource
    BranchMapper branchMapper;
    @Resource
    ProductSubMapper productSubMapper;

    @Resource
    LogProductImgFromUserMapper logProductImgFromUserMapper;


    @Autowired
    BaiduRecUtil baiduRecUtil;


    @Autowired
    YpRecUtilWithPlateService ypRecUtilWithPlateService;

    @Autowired
    YpRecUtilWithPlateAndNoCutService ypRecUtilWithPlateAndNoCutService;

    @Autowired
    BaiduRecUtilWithPallet baiduRecUtilWithPallet;

    @Autowired
    BaiduRecUtilWithPlate baiduRecUtilWithPlate;

    @Autowired
    RuiJingService ruiJingService;

    private String ipAddress;

    private List<Integer> directoryCreatedShopIdList = new ArrayList<>();

    private BASE64Decoder decoder = new BASE64Decoder();

    public ProductController(){
        this.ipAddress = System.getenv().get("ipAddress");

        File file = new File("/opt");

        if (!file.exists()) {
            file.mkdir();
        }

        file = new File("/opt/img");
        if (!file.exists()) {
            file.mkdir();
        }


        file = new File("/opt/img/yppos/");
        if (!file.exists()) {
            file.mkdir();
        }

        file = new File("/usr/local/nginx/html");
        if (!file.exists()) {
            file.mkdir();
        }

        file = new File("/usr/local/nginx/html/images");
        if (!file.exists()) {
            file.mkdir();
        }


        file = new File("/usr/local/nginx/html/images/source");
        if (!file.exists()) {
            file.mkdir();
        }

        file = new File("/usr/local/nginx/html/images/yppos");
        if (!file.exists()) {
            file.mkdir();
        }


    }

    @PostMapping(value = "/api/product/ruiJingUpdate", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取菜品类目", notes = "通过商户id,测试shopId＝2")
    public Result ruiJingUpdate(@RequestBody @Valid JSONObject jsonObject) {
        Integer deskId = jsonObject.getInteger("deskId");
        Integer userId = jsonObject.getInteger("userId");
        BaseChargeResp resp = ruiJingService.getProductList(deskId);
        if (resp == null){
            return ResultGenerator.genFailResult("菜品更新失败");
        }
        return ResultGenerator.genSuccessResult(ruiJingService.updateFace(deskId,userId));
    }


    @GetMapping(value = "/api/product/img/cur/erase", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除当日图片库", notes = "通过商户id,")
    public Result erase(@RequestParam @NotNull Integer shopId) {

        List<LogProductImgFromUser> logProductImgFromUserList = productService.eraseShopBaiduUrlCur(shopId);

        if (logProductImgFromUserList != null && logProductImgFromUserList.size() > 0) {
            for (LogProductImgFromUser logProductImgFromUser : logProductImgFromUserList) {
                if (logProductImgFromUser.getBranchId() == null) {
                    Product product = productService.getProductById(logProductImgFromUser.getProductId());

                    logProductImgFromUser.setBranchId(product.getStoreid());
                }
                boolean deleted = baiduRecUtil.delImgCurList(logProductImgFromUser.getContSign(), shopId, logProductImgFromUser.getBranchId(), logProductImgFromUser.getBaiduAppId());
                if (deleted) {
                    LogProductImgFromUser temp = new LogProductImgFromUser();
                    temp.setId(logProductImgFromUser.getId());
                    temp.setBaiduDeleted(1);
                    logProductImgFromUserMapper.updateByPrimaryKeySelective(temp);
                }
            }
        }

        Condition productSubCondition = new Condition(ProductSub.class);
        productSubCondition.or().andEqualTo("shopId", shopId);

        productSubMapper.deleteByCondition(productSubCondition);


        return ResultGenerator.genSuccessResult(1);
    }

    @PostMapping(value = "/api/product/version", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取菜品版本", notes = "通过商户id,")
    public Result getCategory(@ApiParam("商户id") @RequestBody ShopProductVersionForm form) {
        ShopProductVersion shopProductVersion =
                productService.getShopProductVersion(form.getShopId(), form.getDeviceId());

        if (shopProductVersion != null) {

            return ResultGenerator.genSuccessResult(shopProductVersion.getProductVersion());
        }
        return ResultGenerator.genSuccessResult(1);
    }

    @GetMapping(value = "/api/product/category", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取菜品类目", notes = "通过商户id,测试shopId＝2")
    public Result getCategory(@ApiParam("商户id") @RequestParam @NotNull Integer shopId) {
        List<MinorCategoryVO> vos = productService.findCategory(shopId);
        return ResultGenerator.genSuccessResult(vos);
    }

    @GetMapping(value = "/api/product/list", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取菜品列表", notes = "通过商户id,一级类目id,二级类目id")
    public Result getProducts(@ApiParam("商户id") @RequestParam @NotNull Integer shopId,
                              @ApiParam("一级类目id") @RequestParam Optional<Integer> majorCategoryId,
                              @ApiParam("二级类目id") @RequestParam Optional<Integer> minorCategoryId,
                              @ApiParam("设备id") @RequestParam(required = false) String deviceId
                              ) {

        logger.info("shopId:{}, deviceId:{}", shopId, deviceId);

        Integer branchId = null;
        if (StringUtils.hasText(deviceId)) {
            branchId = DataLoadService.getBranchId(deviceId,shopId);

            Branch branch = null;
            if (branchId == null || branchId == 0) {
                Condition condition = new Condition(Branch.class);
                condition.or().andEqualTo("shopId", shopId);

                List<Branch> branchList = branchMapper.selectByCondition(condition);

                if (branchList != null && branchList.size() > 0) {
                    branch = branchList.get(0);
                }
            }else {
                branch = branchMapper.selectByPrimaryKey(branchId);
            }
            List<ProductVO> list;
            if (branch != null && branch.getBranchPricetype() != null
                    && branch.getBranchPricetype() == 1
                    ) {
                list = productService.findProductsByTime(shopId, majorCategoryId, minorCategoryId);
            }else {
                if (branchId != null) {
                    list  = productService.findProductsByBranchId(shopId, majorCategoryId, minorCategoryId, branchId);

                    if (list == null || list.size() == 0 ) {
                        list  = productService.findProducts(shopId, majorCategoryId, minorCategoryId);
                    }
                }else{
                    list  = productService.findProducts(shopId, majorCategoryId, minorCategoryId);
                }
            }
            return ResultGenerator.genSuccessResult(list);
        }else{
            List<ProductVO> list  = productService.findProducts(shopId, majorCategoryId, minorCategoryId);

            return ResultGenerator.genSuccessResult(list);
        }
    }
    


    @GetMapping(value = "/api/product/curList", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取当日菜品列表", notes = "通过商户id,一级类目id,二级类目id")
    public Result getCurProducts(@ApiParam("商户id") @RequestParam @NotNull Integer shopId,
                              @ApiParam("一级类目id") @RequestParam Optional<Integer> majorCategoryId,
                              @ApiParam("二级类目id") @RequestParam Optional<Integer> minorCategoryId,
                              @ApiParam("设备id") @RequestParam(required = false) String deviceId
                              ) {

        logger.info("/api/product/curList, shopId:{}, deviceId:{}", shopId, deviceId);

        Integer branchId = null;
        if (StringUtils.hasText(deviceId)) {
            branchId = DataLoadService.getBranchId(deviceId,shopId);

            Branch branch = null;
            if (branchId == null || branchId == 0) {
                if (DataLoadService.shopBranchListMap != null) {
                    List<Branch> branchList = DataLoadService.shopBranchListMap.get(shopId);
                    if (branchList != null && branchList.size() > 0) {
                        branch = branchList.get(0);
                    }
                }
            }

            if (branch == null) {
                if (DataLoadService.branchListMap != null) {
                    branch = DataLoadService.branchListMap.get(branchId);
                }
                if (branch == null) {
                    branch = branchMapper.selectByPrimaryKey(branchId);
                }
            }

            if (branch != null) {
                branchId = branch.getBranchId();
                List<ProductVO> productVOList = productService.findCurProductList(shopId, branchId);
                return ResultGenerator.genSuccessResult(productVOList);
            }
        }
        return ResultGenerator.genSuccessResult(null);
    }


    @PostMapping("/api/product/correct")
    public Result upload(@RequestBody ProductCorrectForm productCorrectForm) {

        try {
            logger.info("productCorrectForm=" + JsonUtil.toJson(productCorrectForm));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        ProductImgModel productImgModel = baiduRecUtil.getProductImgFromCache(productCorrectForm.getProductOrderNo());
        Shop shop = DataLoadService.shopMap.get(productImgModel.getShopId());

        if (shop.getProductRecType() != null && shop.getProductRecType().intValue() == 4) {
            ypRecUtilWithPlateService.correctProductImg(productCorrectForm);
        }else if (shop.getProductRecType() != null && shop.getProductRecType().intValue() == 5) {
            ypRecUtilWithPlateAndNoCutService.correctProductImg(productCorrectForm);
        }else {
            baiduRecUtil.correctProductImg(productCorrectForm);
        }
        return ResultGenerator.genSuccessResult();
    }


//    @PostMapping("/api/product/recWithLocation")
    public Result recWithLocation(@RequestBody ProductRecForm productRecForm) {
        long startTime = System.currentTimeMillis();
        logger.info("startTime=" + startTime);
        logger.info("productOrderNo=" + productRecForm.getProductOrderNo());
        StringBuffer filePathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/source/");
        filePathStringBuffer.append(productRecForm.getShopId());


        StringBuffer outputFilepathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/yppos/")
                .append(productRecForm.getShopId());

        if (!directoryCreatedShopIdList.contains(productRecForm.getShopId())) {
            directoryCreatedShopIdList.add(productRecForm.getShopId());
            File dir = new File(filePathStringBuffer.toString());
            File dirOutput = new File(outputFilepathStringBuffer.toString());
            if (!dir.exists()) {
                dir.mkdir();
            }
            if (!dirOutput.exists()) {
                dirOutput.mkdir();
            }
        }

        String uuid = UUID.randomUUID().toString();

        String newFileName = filePathStringBuffer.append("/").append(uuid).append(".png").toString();

        String outputFilepath = outputFilepathStringBuffer.append("/").append(uuid).append(".result.png").toString();

        try {
            Integer[] imgWidthAndHeight = ImageBase64Util.base64StringToImage(productRecForm.getFileContent(), newFileName);

            if (imgWidthAndHeight == null) {
                return ResultGenerator.genFailResult("文件上传失败");
            }

            logger.info("上传成功:newFileName==" + newFileName);

            long endTime = System.currentTimeMillis();
            logger.info("endTime=" + endTime + ", intelval=" + (endTime - startTime));

            ProductRecResultVONewWithLocation result = null;

            StringBuffer imgUrl = new StringBuffer("http://")
                    .append(ipAddress)
                    .append(":8019/images/yppos/")
                    .append(productRecForm.getShopId())
                    .append("/").append(uuid).append(".result.png");

            StringBuffer sourceImgUrl = new StringBuffer("http://")
                    .append(ipAddress)
                    .append(":8019/images/source/")
                    .append(productRecForm.getShopId())
                    .append("/").append(uuid).append(".png");

            Integer branchId = null;
            if (DataLoadService.deviceBaiduShopIdMap != null) {
                branchId = DataLoadService.getBranchId(productRecForm.getDeviceId(), productRecForm.getShopId());
            }


            if (StringUtils.hasText(productRecForm.getProductOrderNo())) {
                result = baiduRecUtil.searchImgNewWithProductOrderNo(productRecForm.getProductOrderNo(), outputFilepath);
            }
            if (result == null) {
                result = baiduRecUtil.searchImgNewWithLocation(branchId,
                        productRecForm.getShopId(), productRecForm.getFileContent()
                        , newFileName, outputFilepath, uuid, imgWidthAndHeight, imgUrl.toString(), sourceImgUrl.toString());
            }

            if (result != null) {
                result.setProductOrderNo(uuid);
                result.setImgUrl(imgUrl.toString());
                logger.info(JsonUtil.toJson(result));
                return ResultGenerator.genSuccessResult(result);
            }
            return ResultGenerator.genFailResult("error");
        } catch (Exception e) {
            logger.info(e.toString());
        }

        ProductRecResultVO result = new ProductRecResultVO();



        StringBuffer url = new StringBuffer("http://")
                .append(ipAddress)
                .append(":8019/images/source/")
                .append(uuid).append(".png");
        result.setImgUrl(url.toString());
        result.setRealFee(1000l);
        result.setTotalFee(1000l);
        result.setProductCount(1);
        result.setProductList(new ArrayList<>());
        result.getProductList().add(new ProductRecResultDetailVO());
        result.getProductList().get(0).setItemCount(1);
        result.getProductList().get(0).setProductId(1);
        result.getProductList().get(0).setProductName("未知菜品");
        result.getProductList().get(0).setProductPrice(1000l);
        result.getProductList().get(0).setSeq(1);

        return ResultGenerator.genSuccessResult(result);
    }



    @PostMapping("/api/product/recWithLocation")
    public Result recWithLocationAndHuawei(@RequestBody ProductRecForm productRecForm) {
        long startTime = System.currentTimeMillis();
        logger.info("recWithLocation startTime=" + startTime);
        StringBuffer filePathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/source/");
        filePathStringBuffer.append(productRecForm.getShopId());

        StringBuffer outputFilepathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/yppos/")
                .append(productRecForm.getShopId());

        if (!directoryCreatedShopIdList.contains(productRecForm.getShopId())) {
            File dirOutput = new File(outputFilepathStringBuffer.toString());
            File dir = new File(filePathStringBuffer.toString());
            directoryCreatedShopIdList.add(productRecForm.getShopId());
            if (!dir.exists()) {
                dir.mkdir();
            }
            if (!dirOutput.exists()) {
                dirOutput.mkdir();
            }
        }

        String uuid = UUID.randomUUID().toString();

        String newFileName = filePathStringBuffer.append("/").append(uuid).append(".png").toString();

        String outputFilepath = outputFilepathStringBuffer.append("/").append(uuid).append(".result.png").toString();

        String tempSourceUrl = "";
        try {
            Shop shop = DataLoadService.shopMap.get(productRecForm.getShopId());

            logger.info("shop.getProductRecType()==={}", shop.getProductRecType());
            ProductRecResultVONewWithLocation result = null;

            StringBuffer imgUrl = null;

            if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 5) {


                long endTime = System.currentTimeMillis();
                logger.info("endTime=" + endTime + ", intelval=" + (endTime - startTime));

                Integer branchId = null;
                if (DataLoadService.deviceBranchIdMap != null) {
                    branchId = DataLoadService.getBranchId(productRecForm.getDeviceId(), productRecForm.getShopId());
                }

                if (branchId == null) {
                    Condition condition = new Condition(Branch.class);
                    condition.or().andEqualTo("shopId", shop.getId());
                    List<Branch> branchList = branchMapper.selectByCondition(condition);
                    if (branchList != null && branchList.size() > 0) {
                        branchId = branchList.get(0).getBranchId();

                        CashierDesk cashierDesk = new CashierDesk();
                        cashierDesk.setBranchid(branchId);
                        cashierDesk.setShopid(shop.getId());
                        DataLoadService.deviceBranchIdMap.put(productRecForm.getDeviceId(), cashierDesk);

                    }else {
                        return ResultGenerator.genFailResult("无分店");
                    }

                }
                StringBuffer sourceImgUrl = new StringBuffer("http://")
                        .append(ipAddress)
                        .append(":8019/images/source/")
                        .append(branchId)
                        .append("/").append(uuid).append(".png");

                tempSourceUrl = sourceImgUrl.toString();

                imgUrl = new StringBuffer("http://")
                        .append(ipAddress)
                        .append(":8019/images/yppos/")
                        .append(branchId)
                        .append("/").append(uuid).append(".result.png");


                logger.info("上传成功:branchId==" + branchId);
                newFileName = newFileName.replace("/" + productRecForm.getShopId(), "/" + branchId);
                outputFilepath = outputFilepath.replace("/" + productRecForm.getShopId(), "/" + branchId);

                logger.info("上传成功:newFileName==" + newFileName);
                logger.info("上传成功:outputFilepath==" + outputFilepath);
                if (result == null) {
                    result = ypRecUtilWithPlateAndNoCutService.searchWithPalletCell(productRecForm.getShopId(), productRecForm.getFileContent()
                            , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                            ,  branchId, productRecForm.getType());
                }
            }else{

                imgUrl = new StringBuffer("http://")
                        .append(ipAddress)
                        .append(":8019/images/yppos/")
                        .append(shop.getId())
                        .append("/").append(uuid).append(".result.png");

                byte[] bytes1 = decoder.decodeBuffer(productRecForm.getFileContent());
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
                BufferedImage bi1 = ImageIO.read(bais);

                File f1 = new File(newFileName);
                ImageIO.write(bi1, "png", f1);


                logger.info("上传成功:newFileName==" + newFileName);

                long endTime = System.currentTimeMillis();
                logger.info("endTime=" + endTime + ", intelval=" + (endTime - startTime));



                StringBuffer sourceImgUrl = new StringBuffer("http://")
                        .append(ipAddress)
                        .append(":8019/images/source/")
                        .append(productRecForm.getShopId())
                        .append("/").append(uuid).append(".png");

                tempSourceUrl = sourceImgUrl.toString();

                Integer branchId = null;
                if (DataLoadService.deviceBranchIdMap != null) {

                    branchId = DataLoadService.getBranchId(productRecForm.getDeviceId(), productRecForm.getShopId());
                }

                if (result == null) {

                    if (shop.getProductRecType() != null && shop.getProductRecType().intValue() == 2) {
                        //托盘格子识别
                        result = baiduRecUtilWithPallet.searchWithPalletCell(productRecForm.getShopId(), productRecForm.getFileContent()
                                , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                                ,  branchId, productRecForm.getType(), bi1.getWidth());
                    } else if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 3) {
                        result = baiduRecUtilWithPlate.searchWithPalletCell(productRecForm.getShopId(), productRecForm.getFileContent()
                                , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                                ,  branchId, productRecForm.getType(), bi1.getWidth());
                    } else if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 4) {
                        result = ypRecUtilWithPlateService.searchWithPalletCell(productRecForm.getShopId(), productRecForm.getFileContent()
                                , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                                ,  branchId, productRecForm.getType(), bi1.getWidth(), bi1);
                    }else {
                        result = baiduRecUtil.search(productRecForm.getShopId(), productRecForm.getFileContent()
                                , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                                ,  branchId, productRecForm.getType(), bi1.getWidth());
                    }

                }
            }



            if (result != null) {
                result.setProductOrderNo(uuid);
                result.setImgUrl(imgUrl.toString());
                logger.info(JsonUtil.toJson(result));
                return ResultGenerator.genSuccessResult(result);
            }
            return ResultGenerator.genFailResult("error");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.toString());
        }

        ProductRecResultVO result = new ProductRecResultVO();

        result.setImgUrl(tempSourceUrl);

        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping("/api/product/rec3")
    public Result upload3(@RequestParam("file") MultipartFile file,
                          @RequestParam("shopId")Integer shopId,
                          @RequestParam("deviceId")String deviceId,
                          @RequestParam(value = "productOrderNo", required = false)String productOrderNo,
                          @RequestParam(value = "recType", required = false)Integer recType,
                          HttpServletResponse response) {

        if (file.isEmpty()) {
            throw new ServiceException("上传失败，请选择文件");
        }

        File tempDir = new File("/opt/img/yppos/" + shopId);
        if (!tempDir.exists()) {
            tempDir.mkdir();
        }

        String filePath = "/opt/img/yppos/" + shopId + "/" + System.currentTimeMillis() + ".jpg";
        File dest = new File(filePath);

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String content = ImageBase64Util.getImageBinary(filePath);


        long startTime = System.currentTimeMillis();
        logger.info("recWithLocation startTime=" + startTime);
        StringBuffer filePathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/source/");
        filePathStringBuffer.append(shopId);

        StringBuffer outputFilepathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/yppos/")
                .append(shopId);

        if (!directoryCreatedShopIdList.contains(shopId)) {
            File dirOutput = new File(outputFilepathStringBuffer.toString());
            File dir = new File(filePathStringBuffer.toString());
            directoryCreatedShopIdList.add(shopId);
            if (!dir.exists()) {
                dir.mkdir();
            }
            if (!dirOutput.exists()) {
                dirOutput.mkdir();
            }
        }

        String uuid = UUID.randomUUID().toString();

        String newFileName = filePathStringBuffer.append("/").append(uuid).append(".png").toString();

        String outputFilepath = outputFilepathStringBuffer.append("/").append(uuid).append(".result.png").toString();

        String tempSourceUrl = "";
        try {
            Shop shop = DataLoadService.shopMap.get(shopId);

            logger.info("shop.getProductRecType()==={}", shop.getProductRecType());
            ProductRecResultVONewWithLocation result = null;

            StringBuffer imgUrl = null;

            if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 5) {


                long endTime = System.currentTimeMillis();
                logger.info("endTime=" + endTime + ", intelval=" + (endTime - startTime));

                Integer branchId = null;
                if (DataLoadService.deviceBranchIdMap != null) {
                    branchId = DataLoadService.getBranchId(deviceId, shopId);
                }
                StringBuffer sourceImgUrl = new StringBuffer("http://")
                        .append(ipAddress)
                        .append(":8019/images/source/")
                        .append(branchId)
                        .append("/").append(uuid).append(".png");

                tempSourceUrl = sourceImgUrl.toString();

                imgUrl = new StringBuffer("http://")
                        .append(ipAddress)
                        .append(":8019/images/yppos/")
                        .append(branchId)
                        .append("/").append(uuid).append(".result.png");

                if (branchId == null) {
                    Condition condition = new Condition(Branch.class);
                    condition.or().andEqualTo("shopId", shop.getId());
                    List<Branch> branchList = branchMapper.selectByCondition(condition);
                    if (branchList != null && branchList.size() > 0) {
                        branchId = branchList.get(0).getBranchId();

                        CashierDesk cashierDesk = new CashierDesk();
                        cashierDesk.setBranchid(branchId);
                        cashierDesk.setShopid(shop.getId());
                        DataLoadService.deviceBranchIdMap.put(deviceId, cashierDesk);

                    }else {
                        return ResultGenerator.genFailResult("无分店");
                    }

                }

                logger.info("上传成功:branchId==" + branchId);
                newFileName = newFileName.replace("/" + shopId, "/" + branchId);
                outputFilepath = outputFilepath.replace("/" + shopId, "/" + branchId);

                logger.info("上传成功:newFileName==" + newFileName);
                logger.info("上传成功:outputFilepath==" + outputFilepath);
                if (result == null) {
                    result = ypRecUtilWithPlateAndNoCutService.searchWithPalletCell(shopId, content
                            , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                            ,  branchId, recType);
                }
            }else{

                imgUrl = new StringBuffer("http://")
                        .append(ipAddress)
                        .append(":8019/images/yppos/")
                        .append(shop.getId())
                        .append("/").append(uuid).append(".result.png");

                byte[] bytes1 = decoder.decodeBuffer(content);
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
                BufferedImage bi1 = ImageIO.read(bais);

                File f1 = new File(newFileName);
                ImageIO.write(bi1, "png", f1);


                logger.info("上传成功:newFileName==" + newFileName);

                long endTime = System.currentTimeMillis();
                logger.info("endTime=" + endTime + ", intelval=" + (endTime - startTime));



                StringBuffer sourceImgUrl = new StringBuffer("http://")
                        .append(ipAddress)
                        .append(":8019/images/source/")
                        .append(shopId)
                        .append("/").append(uuid).append(".png");

                tempSourceUrl = sourceImgUrl.toString();

                Integer branchId = null;
                if (DataLoadService.deviceBranchIdMap != null) {

                    branchId = DataLoadService.getBranchId(deviceId, shopId);
                }

                if (result == null) {

                    if (shop.getProductRecType() != null && shop.getProductRecType().intValue() == 2) {
                        //托盘格子识别
                        result = baiduRecUtilWithPallet.searchWithPalletCell(shopId, content
                                , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                                ,  branchId, recType, bi1.getWidth());
                    } else if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 3) {
                        result = baiduRecUtilWithPlate.searchWithPalletCell(shopId, content
                                , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                                ,  branchId, recType, bi1.getWidth());
                    } else if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 4) {
                        result = ypRecUtilWithPlateService.searchWithPalletCell(shopId, content
                                , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                                ,  branchId, recType, bi1.getWidth(), bi1);
                    }else {
                        result = baiduRecUtil.search(shopId, content
                                , newFileName, outputFilepath, uuid, imgUrl.toString(), sourceImgUrl.toString()
                                ,  branchId, recType, bi1.getWidth());
                    }

                }
            }



            if (result != null) {
                result.setProductOrderNo(uuid);
                result.setImgUrl(imgUrl.toString());
                logger.info(JsonUtil.toJson(result));
                return ResultGenerator.genSuccessResult(result);
            }
            return ResultGenerator.genFailResult("error");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.toString());
        }

        ProductRecResultVO result = new ProductRecResultVO();


        result.setImgUrl(tempSourceUrl);

        return ResultGenerator.genSuccessResult(result);
    }




    /*public static void main(String[] args) throws Exception {
        *//*String filePath = "/opt/img/yppos/124/" + System.currentTimeMillis() + ".jpg";
        File file = new File(filePath);
        try {

            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write("aaa".getBytes());

            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }*//*

        String filepath = "/Users/jay/IdeaProjects/binguo/api/target/aab.zip";

        unZip(new File(filepath), "/Users/jay/IdeaProjects/binguo/api/target");

        //
        File src = new File("/Users/jay/IdeaProjects/binguo/api/target/安装文档2.docx");

        if (!src.exists()) {
            throw new RuntimeException("" + "不存在");
        }
        File zipFile = new File("/Users/jay/IdeaProjects/binguo/api/target/aabb.zip");

        try {

            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);
            String baseDir = "/Users/jay/IdeaProjects/binguo/api/target/";
            compressbyType(src, zos, baseDir);
            zos.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

    }*/

    /**
     * 按照原路径的类型就行压缩。文件路径直接把文件压缩，
     * @param src
     * @param zos
     * @param baseDir
     */
    private static void compressbyType(File src, ZipOutputStream zos,String baseDir) {

        if (!src.exists())
            return;
        logger.info("压缩路径" + baseDir + src.getName());
        //判断文件是否是文件，如果是文件调用compressFile方法,如果是路径，则调用compressDir方法；
        if (src.isFile()) {
            //src是文件，调用此方法
            compressFile(src, zos, baseDir);

        }

    }

    /**
     * 压缩文件
     */
    private static void compressFile(File file, ZipOutputStream zos,String baseDir) {
        if (!file.exists())
            return;
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry = new ZipEntry(baseDir + file.getName());
            zos.putNextEntry(entry);
            int count;
            byte[] buf = new byte[1024];
            while ((count = bis.read(buf)) != -1) {
                zos.write(buf, 0, count);
            }
            bis.close();

        } catch (Exception e) {
            // TODO: handle exception

        }
    }

    /**
     * zip解压
     * @param srcFile        zip源文件
     * @param destDirPath     解压后的目标文件夹
     * @throws RuntimeException 解压失败会抛出运行时异常
     */
    public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
        long start = System.currentTimeMillis();
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                logger.info("解压" + entry.getName());
                // 如果是文件夹，就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if(!targetFile.getParentFile().exists()){
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[is.available()];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
            long end = System.currentTimeMillis();
            logger.info("解压完成，耗时：" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        } finally {
            if(zipFile != null){
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
